package com.hunt.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hunt.app.filter.JWTTokenUtil;
import com.hunt.model.entity.UserInfo;
import com.hunt.service.UserInfoService;
import com.hunt.util.AuroraUtil;
import com.hunt.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;

import static com.hunt.util.AuroraUtil.PRIVATE_KEY;

/**
 * @Author: sjs
 * @Date : 2020/10/21
 */

@Api("极光推送模块")
@Controller
@RequestMapping("/app/auroraPush")
public class AuroraPushController extends BaseController {


    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private JedisPool jedisPool;

    @ApiOperation(value = "查询权限列表", httpMethod = "POST", produces = "application/json", response = Result.class)
    @ResponseBody
    @RequestMapping(value = "auth", method = RequestMethod.POST)
    public Result auth(/*@RequestParam String url,*/
            @RequestParam String loginToken/*,
                       @RequestParam(required = false) String appKey,
                       @RequestParam(required = false) String masterKey*/) {

        String url = "https://api.verification.jpush.cn/v1/web/loginTokenVerify";
        String appKey = AuroraUtil.APP_KEY;
        String masterKey = AuroraUtil.MASTER_KEY;

        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = null;
        String responseContent = "";
        try {
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json");
            httpPost.addHeader("Authorization", "Basic " +
                    Base64.getUrlEncoder().encodeToString((appKey + ":" + masterKey).getBytes()));
            JSONObject json = new JSONObject();
            json.put("loginToken", loginToken);
            json.put("appKey", appKey);
            json.put("masterKey", masterKey);
            json.put("url", url);

            httpPost.setEntity(new StringEntity(JSON.toJSONString(json)));

            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            responseContent = EntityUtils.toString(entity, "UTF-8");
            response.close();
            httpClient.close();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 释放资源
                if (httpClient != null) {
                    httpClient.close();
                }
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        JSONObject responseJson = JSON.parseObject(responseContent);

        String phoneValue = (String) responseJson.get("phone");
        String code = null;
        try {
            if (phoneValue == null) {
                return Result.error();
            }
            //得到解密后的phone值
            code = AuroraUtil.decrypt(phoneValue, PRIVATE_KEY);
            System.out.println("code: " + code);

        } catch (Exception e) {
            e.printStackTrace();
        }
        UserInfo userInfo = userInfoService.userInfoEncrypt(code);
        if(userInfo==null){
            return  Result.error();
        }
        String token = JWTTokenUtil.createToken(userInfo.getUserid(), userInfo.getPwd(), userInfo.getUserlevel());
        userInfo.setToken(token);
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            HashMap<String, String> map = new HashMap<>();
            map.put(userInfo.getUserid(),token);
            jedis.hmset("app_token_check",map);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        byte[] userInfoBytes = JSON.toJSONString(userInfo).getBytes();

     // Base64 加密
        String userInfoEncoded = Base64.getEncoder().encodeToString(userInfoBytes);

        return Result.success(userInfoEncoded);
    }


}
